package com.hfut.manage.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hfut.manage.pojo.Dash;
import com.hfut.manage.pojo.Department;
import com.hfut.manage.pojo.Result;
import com.hfut.manage.pojo.Teacher;
import com.hfut.manage.service.IDepartmentService;
import com.hfut.manage.service.ITeacherService;
import com.hfut.manage.service.ITitleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/dash")
public class DashboardController {
    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private ITeacherService teacherService;

    @GetMapping("/header")
    public Result list() {
        Integer teacherNum = teacherService.list().size();
        Integer deptNum = departmentService.list().size();
        List<Map<String, Object>> titleResult = teacherService.listMaps(
                new QueryWrapper<Teacher>()
                        .select("title, COUNT(*) as count")
                        .groupBy("title")
        );

        Map<String, Object> avgAgeResult = teacherService.getMap(
                new QueryWrapper<Teacher>()
                        .select("avg(YEAR(FROM_DAYS(DATEDIFF(NOW(),birth_date)))) as AvgAge")
        );
        double avgAge = 0;
        if (avgAgeResult != null && avgAgeResult.get("AvgAge") != null) {
            Object ageValue = avgAgeResult.get("AvgAge");
            if (ageValue instanceof Number) {
                avgAge = ((Number) ageValue).doubleValue();
            }
        }
        List<Map<String, Object>> deptResult = teacherService.listMaps(
                new QueryWrapper<Teacher>()
                        .select("department, COUNT(*) as count")
                        .groupBy("department")
        );

        Dash dash = Dash.getInstance(teacherNum, deptNum, avgAge, titleResult, deptResult);
        return Result.success(dash);
    }



}
